import React, { useEffect } from "react";
import { 
  StyleSheet, 
  Text, 
  View, 
  ScrollView,
  TouchableOpacity
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { Clock, Calendar as CalendarIcon, Award, ChevronRight } from "lucide-react-native";
import { colors } from "@/constants/colors";
import { Card } from "@/components/Card";
import { StatsChart } from "@/components/StatsChart";
import { CalendarView } from "@/components/CalendarView";
import { useAuthStore } from "@/store/auth-store";
import { useStudyStore } from "@/store/study-store";

export default function StatsScreen() {
  const { user } = useAuthStore();
  const { checkIns, getStats, checkIn, makeupCheckIn } = useStudyStore();
  
  // Get user stats
  const stats = user ? getStats(user.id) : null;
  
  // Format time (minutes to hours and minutes)
  const formatTime = (minutes: number) => {
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    
    if (hours > 0) {
      return `${hours}h ${mins}m`;
    } else {
      return `${mins}m`;
    }
  };
  
  // Format data for charts
  const weeklyChartData = stats?.weeklyData.map(item => ({
    label: new Date(item.date).toLocaleDateString(undefined, { weekday: 'short' }),
    value: item.minutes,
    color: colors.primary,
  })) || [];
  
  const contentTypeChartData = stats?.contentTypeDistribution.map(item => ({
    label: item.type,
    value: item.minutes,
    color: item.type === 'Words' ? colors.primary : 
           item.type === 'Phrases' ? colors.secondary : 
           item.type === 'Sentences' ? colors.accent : 
           colors.success,
  })) || [];
  
  const difficultyChartData = stats?.difficultyDistribution.map(item => ({
    label: item.level,
    value: item.minutes,
    color: item.level === 'Beginner' ? colors.success : 
           item.level === 'Intermediate' ? colors.secondary : 
           colors.accent,
  })) || [];
  
  // Handle check-in
  const handleCheckIn = (date: string) => {
    if (user) {
      checkIn(user.id, date);
    }
  };
  
  // Handle makeup check-in
  const handleMakeupCheckIn = (date: string) => {
    if (user) {
      makeupCheckIn(user.id, date);
    }
  };
  
  return (
    <SafeAreaView style={styles.container} edges={["top"]}>
      <ScrollView style={styles.scrollView} contentContainerStyle={styles.scrollContent}>
        <Text style={styles.title}>Learning Stats</Text>
        
        {/* Summary cards */}
        <View style={styles.summaryContainer}>
          <Card style={styles.summaryCard} variant="elevated">
            <View style={styles.summaryIconContainer}>
              <Clock size={24} color={colors.primary} />
            </View>
            <Text style={styles.summaryValue}>
              {stats ? formatTime(stats.totalTime) : '0m'}
            </Text>
            <Text style={styles.summaryLabel}>Total Study Time</Text>
          </Card>
          
          <Card style={styles.summaryCard} variant="elevated">
            <View style={styles.summaryIconContainer}>
              <CalendarIcon size={24} color={colors.secondary} />
            </View>
            <Text style={styles.summaryValue}>
              {user?.streak || 0}
            </Text>
            <Text style={styles.summaryLabel}>Day Streak</Text>
          </Card>
          
          <Card style={styles.summaryCard} variant="elevated">
            <View style={styles.summaryIconContainer}>
              <Award size={24} color={colors.accent} />
            </View>
            <Text style={styles.summaryValue}>
              {stats ? formatTime(stats.dailyAverage) : '0m'}
            </Text>
            <Text style={styles.summaryLabel}>Daily Average</Text>
          </Card>
        </View>
        
        {/* Weekly progress chart */}
        <StatsChart
          title="Weekly Study Time"
          data={weeklyChartData}
          type="bar"
          height={200}
        />
        
        {/* Content type distribution */}
        <StatsChart
          title="Content Type Distribution"
          data={contentTypeChartData}
          type="pie"
          height={200}
        />
        
        {/* Difficulty distribution */}
        <StatsChart
          title="Difficulty Level Distribution"
          data={difficultyChartData}
          type="bar"
          height={200}
        />
        
        {/* Calendar check-in */}
        <View style={styles.calendarContainer}>
          <View style={styles.sectionHeader}>
            <Text style={styles.sectionTitle}>Check-in Calendar</Text>
            <TouchableOpacity>
              <Text style={styles.seeAll}>View All</Text>
            </TouchableOpacity>
          </View>
          
          <CalendarView
            checkIns={checkIns}
            userId={user?.id || ''}
            onCheckIn={handleCheckIn}
            onMakeupCheckIn={handleMakeupCheckIn}
          />
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  scrollView: {
    flex: 1,
  },
  scrollContent: {
    padding: 16,
  },
  title: {
    fontSize: 24,
    fontWeight: "700",
    color: colors.text.primary,
    marginBottom: 24,
  },
  summaryContainer: {
    flexDirection: "row",
    justifyContent: "space-between",
    marginBottom: 24,
  },
  summaryCard: {
    flex: 1,
    marginHorizontal: 4,
    alignItems: "center",
    paddingVertical: 16,
  },
  summaryIconContainer: {
    width: 48,
    height: 48,
    borderRadius: 24,
    backgroundColor: colors.card,
    justifyContent: "center",
    alignItems: "center",
    marginBottom: 8,
  },
  summaryValue: {
    fontSize: 20,
    fontWeight: "700",
    color: colors.text.primary,
    marginBottom: 4,
  },
  summaryLabel: {
    fontSize: 12,
    color: colors.text.secondary,
    textAlign: "center",
  },
  sectionHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    marginBottom: 16,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: "600",
    color: colors.text.primary,
  },
  seeAll: {
    fontSize: 14,
    color: colors.primary,
    fontWeight: "500",
  },
  calendarContainer: {
    marginBottom: 24,
  },
});